<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button
						type="warning"
						:loading="exportLoading"
						icon="el-icon-upload2"
						size="small"
						class="item-gap"
						@click="onExportExcel"
					>导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<div class="flex-end-center-wrap">
						<jk-select v-model="searchParams.workshopId" :option-list="workshopList" clearable placeholder="区域" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="areaOnChange"></jk-select>
						<jk-select v-model="searchParams.processCode" clearable placeholder="工序" value-key-name="code" :option-list="processList" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
						<jk-date-picker v-model="searchParams.belongDate" :clearable="false" type="daterange" style="width: 280px;" placeholder="日期" :picker-options="pickerOptions" size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-date-picker>
						<jk-select v-model="searchParams.shiftId" clearable placeholder="班次" :option-list="shiftList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="shiftOnChange"></jk-select>
					</div>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="frontGroupSalaryMonthReportTable"
				:loading="tableLoading"
				border
				:stripe="false"
				:data="tableData"
				show-footer
				:footer-method="footerMethod"
				:height="tableHeight + 20"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.keyName === 'runningEfficiency'">{{ scope.row.runningEfficiency + '%' }}</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { systemUserColumnConfigGet } from '@/api/system/column-config';
    import {
        productionMachineShiftOutputGetMachineEfficiencyTop
    } from '@/api/production/machineEfficiencyTable';
    import { workforcemanagementShiftPage } from '@/api/schedule/shift';
    import XEUtils from 'xe-utils';
    import { mathJsAdd } from '@/utils/jk/jk-cals';
    export default {
        name: 'MachineEfficiencyTable',
        components: {},
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': productionMachineShiftOutputGetMachineEfficiencyTop
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                totalData: {
                    totalOutputM: 0,
                    totalOutputKg: 0
                },
                tableColumnList: [],
                processList: [],
                tableData: [],
                shiftList: [],
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                noCalKey: ['runningEfficiency'],
                searchParams: {
                    belongDate: [],
                    count: 0,
                    processCode: '',
                    shiftId: '',
                    shiftName: '',
                    workshopId: null,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize
                }
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return `平均效率`;
                        }
                        // if (this.noCalKey.includes(column.property)) {
                        //     val1 = mathJsAdd(val1, data.fullQty);
                        //     // return XEUtils.sum(data, column.property);
                        //     return this.calTotal(data, column.property);
                        // }
                        if (column.property === 'runningEfficiency') {
                            return (XEUtils.sum(data, column.property) / data.length).toFixed(2) + '%';
                        }
                        return null;
                    })
                ];
            },
            calTotal(data, key) {
                let val = 0;
                data.forEach(x => {
                    val = mathJsAdd(x[key] || 0, val);
                });
                return val;
            },
            /** 导出按钮操作 */
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.endDate = params.belongDate[1];
                params.startDate = params.belongDate[0];
                delete params.belongDate;
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(
                    () => {
                        this.exportLoading = true;
                        return productionMachineShiftOutputGetMachineEfficiencyTop(params);
                    }).then(res => {
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = this.tableColumnList.map(x => x.title);
                            const filterVal = this.tableColumnList.map(x => x.keyName);
                            const list = res.data.res || [];
                            list.forEach(x => {
                                x.runningEfficiency = x.runningEfficiency + '%';
                            });
                            // 合计项
                            const totalItem = {};
                            filterVal.forEach((x, idx) => {
                                totalItem[x] = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0][idx];
                            });
                            list.push(totalItem);
                            const data = list.map(v => filterVal.map(j => v[j]));
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: `${this.$route.meta.title}(${formatDate(Date.now())})`,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                    this.exportLoading = false;
                });
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'MachineEfficiencyTable', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            areaOnChange() {
                this.$set(this.searchParams, 'shiftId', '');
                this.$set(this.searchParams, 'shiftName', '');
                if (!this.searchParams.workshopId) {
                    this.shiftList = [];
                } else {
                    this.getShiftListRequest();
                }
            },
            shiftOnChange(val) {
                this.shiftList.find(x => {
                    if (x.id === val) {
                        this.searchParams.shiftName = x.name;
                    }
                }
                );
            },
            // 获取所有班次
            getShiftListRequest: function() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                delete params.shiftId;
                delete params.count;
                delete params.yarnCount;
                delete params.belongDate;
                delete params.processCode;
                params.auditState = 1;
                return workforcemanagementShiftPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                if (this.searchParams.belongDate.length === 0) {
                    this.searchParams.belongDate = [formatDate(Date.now()), formatDate(Date.now())];
                }
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.processList = this.$store.state.user.userProcess.processList;
                if (!this.searchParams.processCode) {
                    this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || 'XS');
                }
                if (!this.searchParams.workshopId) {
                    this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                await this.getShiftListRequest();
                if (!this.searchParams.shiftId) {
                    this.$set(this.searchParams, 'shiftId', this.shiftList && this.shiftList[0].id ? this.shiftList[0].id : null);
                }
                if (!this.searchParams.shiftName) {
                    this.$set(this.searchParams, 'shiftName', this.shiftList && this.shiftList[0].name ? this.shiftList[0].name : null);
                }
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.endDate = params.belongDate[1];
                params.startDate = params.belongDate[0];
                delete params.belongDate;
                // delete params.shiftId;
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    this.searchParams.count = res.data.count;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res ? res.data.res.map(x => {
                            return x;
                        }) : [];
                        this.totalData = res.data.res;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                if (!this.searchParams.shiftName || !this.searchParams.shiftId) {
                    this.tableData = [];
                }
                this.getListRequest();
            }
        }
    };
</script>
<style>
.machine-group-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-left: solid 1px #eee;
  border-top: solid 1px #eee;
  width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 4px;
  flex-shrink: 0;
}
</style>
